package com.yuan.config;


import com.yuan.websocket.handler.PlusWebSocketHandler;
import com.yuan.websocket.interceptor.PlusWebSocketInterceptor;
import com.yuan.websocket.listener.WebSocketTopicListener;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

@Configuration
@EnableWebSocket
public class WebSocketConfig {

    @Bean
    public WebSocketConfigurer webSocketConfigurer(HandshakeInterceptor handshakeInterceptor,  WebSocketHandler webSocketHandler) {
        // 如果WebSocket的路径为空，则设置默认路径为 "/websocket"
        System.out.println("webSocketConfigurer===============");
        // 返回一个WebSocketConfigurer对象，用于配置WebSocket
        return registry -> registry
                // 添加WebSocket处理程序和拦截器到指定路径，设置允许的跨域来源
                .addHandler(webSocketHandler, "/websocket")
                .addInterceptors(handshakeInterceptor)
                .setAllowedOrigins("*");
    }

    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        // 设置文本消息缓冲区为 32KB，二进制消息缓冲区为 64KB
        container.setMaxTextMessageBufferSize(32 * 1024);
        container.setMaxBinaryMessageBufferSize(64 * 1024);
        return container;
    }

    @Bean
    public HandshakeInterceptor handshakeInterceptor() {
        return new PlusWebSocketInterceptor();
    }

    @Bean
    public WebSocketHandler webSocketHandler() {
        return new PlusWebSocketHandler();
    }

    @Bean
    public WebSocketTopicListener topicListener() {
        return new WebSocketTopicListener();
    }


}
